package com.gomore.opple.module.addcustomer;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gomore.opple.R;
import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.model.EventPhoto;
import com.gomore.opple.model.ReflahEvent;
import com.gomore.opple.model.StoreAddress;
import com.gomore.opple.module.BaseFragment;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.utils.DensityUtil;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.web.cgform.consumer.entity.TOConsumerEntity;
import com.gomore.opple.widgets.XCRoundRectImageView;
import com.gomore.opple.widgets.dialog.ConfirmDialog;
import com.lljjcoder.citypickerview.widget.CityPicker;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


/**
 * Created by robot
 */
public class AddConsumerFragment extends BaseFragment implements AddConsumerContract.View {

    @Bind(R.id.consumer_icon)
    XCRoundRectImageView consumer_icon;
    @Bind(R.id.consumer_name)
    EditText consumer_name;
    @Bind(R.id.consumer_mobile)
    EditText consumer_mobile;
    @Bind(R.id.consumer_company)
    EditText consumer_company;
    @Bind(R.id.select_zone)
    TextView select_zone;
    @Bind(R.id.consumer_address)
    EditText consumer_address;
    @Bind(R.id.save)
    TextView save;
    String province, citys, country;
    private String iconUrl;
    private String id;
    private int height;
    private boolean isCreateConsumer;

    private AddConsumerContract.Presenter mPresenter;
    private TOConsumerEntity toConsumerEntity;

    public static AddConsumerFragment getInstance() {
        return new AddConsumerFragment();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_add_consumer;
    }

    @Override
    protected void initalizeData() {
        EventBus.getDefault().register(this);
        if (getArguments() != null && getArguments().getSerializable(IntentStart.CONSUMER) != null) {
            toConsumerEntity = (TOConsumerEntity) getArguments().getSerializable(IntentStart.CONSUMER);
        }
        height = DensityUtil.dip2px(getActivity(), 80);
    }

    @Override
    protected void initalizeViews() {
        if (toConsumerEntity == null) {
            isCreateConsumer = true;
            toConsumerEntity = new TOConsumerEntity();
            mPresenter.prepareInitData();
        } else {
            isCreateConsumer = false;
            showContentView(toConsumerEntity);
        }
    }


    @Override
    public void setPresenter(AddConsumerContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void goBack(String consumerId) {
        ReflahEvent reflahEvent = new ReflahEvent();
        reflahEvent.setConsumerId(consumerId);
        reflahEvent.setReflash(true);
        EventBus.getDefault().post(reflahEvent);
        getActivity().finish();
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void setUrl(String icon_url) {
        iconUrl = icon_url;
    }

    @Override
    public void setStoreAddress(StoreAddress storeAddress) {
        if (storeAddress.getProvince() != null) {
            province = storeAddress.getProvince();
            citys = storeAddress.getCity();
            country = storeAddress.getCountry();
            select_zone.setText(province + " - " + citys + " - " + country);
        }
    }

    @OnClick({R.id.select_zone, R.id.save, R.id.consumer_icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.select_zone:
                //收起软键盘
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                ZonePicker();
                break;
            case R.id.save:
                saveConsumer(isCreateConsumer);
                break;
            case R.id.consumer_icon:
                IntentStart.getInstance().startTakeAndSelectPhotoActivity(getActivity(), GlobalConstant.FragmentType.ADDCONSUMERFRAGMENT, 0);
                break;
        }
    }

    public void onEventMainThread(EventPhoto eventPhoto) {
        if (eventPhoto != null && eventPhoto.getFragmentType() != null &&
                eventPhoto.getUrl() != null) {
            if (eventPhoto.getFragmentType().equals(GlobalConstant.FragmentType.ADDCONSUMERFRAGMENT)) {
                //显示本地图片
                Glide.with(getActivity())
                        .load(eventPhoto.getUrl())
                        .asBitmap()
                        .override(height, height)
                        .placeholder(R.mipmap.consumer_icon)
                        .into(consumer_icon);
                //上传图片
                File file = new File(eventPhoto.getUrl());
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                mPresenter.saveAttachment(body);
            }
        }
    }

    private void ZonePicker() {
        CityPicker cityPicker = new CityPicker.Builder(getActivity())
                .textSize(20)
                .title("地址选择")
                .backgroundPop(0xa0000000)
                .titleBackgroundColor("#cccccc")
                .titleTextColor("#000000")
                .confirTextColor("#666666")
                .cancelTextColor("#666666")
                .province("江苏省")
                .city("常州市")
                .district("天宁区")
                .textColor(Color.parseColor("#666666"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(5)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();

        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                province = citySelected[0];
                //城市
                citys = citySelected[1].replace(" ", "");
                //区县（如果设定了两级联动，那么该项返回空）
                country = citySelected[2];
                //邮编
                String code = citySelected[3];
                select_zone.setText(province + "-" + citys + "-" + country);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    public void saveConsumer(final boolean isCreateConsumer) {
        if (TextUtils.isEmpty(consumer_name.getText().toString().trim())) {
            showMessage("请填写客户名称");
            return;
        }
        if (TextUtils.isEmpty(consumer_mobile.getText().toString().trim())) {
            showMessage("请填写手机号码");
            return;
        }
        if (!isPhoneNumberValid(consumer_mobile.getText().toString().trim())) {
            showMessage("请填写正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(province)) {
            showMessage("请选择省市区");
            return;
        }
        if (TextUtils.isEmpty(consumer_address.getText().toString().trim())) {
            showMessage("请填写客户地址");
            return;
        }
        toConsumerEntity.setId(id);
        toConsumerEntity.setPicture(iconUrl);
        toConsumerEntity.setName(consumer_name.getText().toString().trim());
        toConsumerEntity.setMobile(consumer_mobile.getText().toString().trim());
        toConsumerEntity.setCompany(consumer_company.getText().toString().trim());
        toConsumerEntity.setProvince(province);
        toConsumerEntity.setCity(citys);
        toConsumerEntity.setCountry(country);
        toConsumerEntity.setAddress(consumer_address.getText().toString().trim());
        //确定框
        ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
        ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
        final String title = "提示";
        String message = "确定保存客户吗?";
        onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                mPresenter.save(toConsumerEntity, isCreateConsumer);
            }
        };
        onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                DialogUtils.cancel();
            }
        };
        DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
    }

    private void showContentView(TOConsumerEntity toConsumerEntity) {
        id = toConsumerEntity.getId();
        String url = "demo";
        if (toConsumerEntity.getPicture() != null) {
            url = toConsumerEntity.getPicture();
            iconUrl = toConsumerEntity.getPicture();
        }
        int height = DensityUtil.dip2px(getActivity(), 80);
        Glide.with(getActivity())
                .load(url)
                .asBitmap()
                .centerCrop()
                .override(height, height)
                .placeholder(R.mipmap.consumer_icon)
                .into(consumer_icon);
        if (toConsumerEntity.getName() != null) {
            consumer_name.setText(toConsumerEntity.getName());
            consumer_name.setSelection(toConsumerEntity.getName().length());
        }
        if (toConsumerEntity.getMobile() != null) {
            consumer_mobile.setText(toConsumerEntity.getMobile());
            consumer_mobile.setSelection(toConsumerEntity.getMobile().length());
        }
        if (toConsumerEntity.getProvince() != null) {
            province = toConsumerEntity.getProvince();
            citys = toConsumerEntity.getCity();
            country = toConsumerEntity.getCountry();
            select_zone.setText(province + " - " + citys + " - " + country);
        }
        if (toConsumerEntity.getCompany() != null) {
            consumer_company.setText(toConsumerEntity.getCompany());
            consumer_company.setSelection(toConsumerEntity.getCompany().length());
        }
        if (toConsumerEntity.getAddress() != null) {
            consumer_address.setText(toConsumerEntity.getAddress());
        }
    }

    //判断是否为电话号码
    private boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        String expression = "((^(13|14|15|17|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
